<?php
require_once "Downloader.php";
require_once "ConfigReader.php";

class Monitor {
    private $folder;
    private $dstFolder;

    public function __construct() {
        $this->folder = ConfigReader::instance()->getMonitoredFolder();
        $this->dstFolder = ConfigReader::instance()->getDestinationFolder();
    }

    public function start() {
        $dir = dir($this->folder);
        while (true) {
            $dir->rewind();
            while (false != ($file = $dir->read())) {
                if (is_dir($file)) {
                    continue;
                }

                $content = file_get_contents($dir->path . '/' . $file);
                if (null == ($json = json_decode($content, true))) {
                    echo "JSON error : " . json_last_error() . "\n";
                    unlink($dir->path . '/' . $file);
                } elseif ($json["state"] == "waiting") {
                    echo "Starting to download : " . $json["destination"] . "\n";
                    if (is_array($json["url"])) {
                        $json["url"] = $json["url"][0];
                    }

                    $dl = new Downloader($json["url"], $this->dstFolder . '/' . $json["destination"]);
                    $json["state"] = $dl->getState();
                    $json["totalSize"] = $dl->getTotalSize();
                    file_put_contents($dir->path . '/' . $file, json_encode($json));
                    if (!$dl->getState() != "error") {
                        $pid = pcntl_fork();
                        if ($pid == -1) {
                            die("Error when forking");
                        } elseif ($pid) {
                            continue;
                        } else {
                            $dl->start($dir->path . '/' . $file);
                            return;
                        }
                    }
                } elseif ($json["state"] == "complete") {
                    //echo $json["destination"] . " finished downloading.\n";
                }
            }
            sleep(2);
        }
    }
}
?>
